﻿// The MIT License (MIT)
// Copyright (c) 2014 LuoZhihui
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the “Software”), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

using System;
using System.IO;
using System.Net.Sockets;

namespace EasyTelnet
{
    /// <summary>
    ///     交换数据流
    /// </summary>
    public class DataStream : MemoryStream
    {
        public DataStream(Socket socket, int capacity)
            : base(capacity)
        {
            WorkSocket = socket;
        }

        public DataStream(Socket socket, byte[] buffer, int index, int count)
            : base(buffer, index, count, true, true)
        {
            WorkSocket = socket;
        }

        public Socket WorkSocket { get; private set; }

        public bool HasData
        {
            get { return Position <= Length; }
        }

        public new byte ReadByte()
        {
            var _byte = (byte) base.ReadByte();
#if DEBUG
            Console.WriteLine("_Read:{0}", _byte);
#endif
            return _byte;
        }

        internal void Write(params byte[] bytes)
        {
#if DEBUG
            foreach (var b in bytes)
            {
                Console.WriteLine("Write:{0}", b);
            }
#endif
            Write(bytes, 0, bytes.Length);
        }

        internal void WriteByte(TelnetCommand command)
        {
            var b = (byte) command;
#if DEBUG
            Console.WriteLine("Write:{0}", b);
#endif
            base.WriteByte(b);
        }

        internal void WriteByte(TelnetOptionQualifier optionQualifier)
        {
            var b = (byte) optionQualifier;
#if DEBUG
            Console.WriteLine("Write:{0}", b);
#endif
            base.WriteByte(b);
        }

        internal void WriteByte(TelnetOption option)
        {
            var b = (byte) option;
#if DEBUG
            Console.WriteLine("Write:{0}", b);
#endif
            base.WriteByte(b);
        }

        public new void WriteByte(byte value)
        {
#if DEBUG
            Console.WriteLine("Write:{0}", value);
#endif
            base.WriteByte(value);
        }

        private byte[] GetDataBlock()
        {
            if (Position < 2) return new byte[0];
            var workBuffer = new byte[Position];
            var allBytes = ToArray();
            for (var i = 0; i < workBuffer.Length && i < allBytes.Length; i++)
            {
                workBuffer[i] = allBytes[i];
            }
            return workBuffer;
        }

        /// <summary>
        ///     重置流位置
        /// </summary>
        public void ResetPosition()
        {
            Seek(0, SeekOrigin.Begin);
        }

        /// <summary>
        ///     发送缓存中的数据
        /// </summary>
        public void SendBuffer()
        {
            if (Position <= 0) return;

            var respBuffer = GetDataBlock();
            if (respBuffer == null || respBuffer.Length <= 0) return;
           // Console.WriteLine("CLIENT:{0}",respBuffer.BytesString());
            WorkSocket.Send(respBuffer, 0, respBuffer.Length, SocketFlags.None);
        }
    }
}